<?php
// +----------------------------------------------------------------------
// | BhAdmin [ BhAdmin匠心打造，我们相信，每个伟大的软件都有一个伟大的故事 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2023 https://www.bhadmin.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed BhAdmin并不是自由软件，未经许可不能去掉BhAdmin相关版权
// +----------------------------------------------------------------------
// | Author: BAIHU  <admin@bhadmin.cn>
// +----------------------------------------------------------------------
namespace app\admin\logic;

use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Service\ConfigService;

class ConfigLogic extends BackendLogic
{
    public function __construct()
    {
        $this->service = Container::get(ConfigService::class);
    }


    public function getList(): array
    {
        $configList = $this->service->getAllList([['mark', '=', 1]], ['*'], ['sort' => 'asc']);
        return message($configList);
    }

    public function edit(): array
    {
        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (empty($data['name'])) throw new ApiException('请输入配置名称');
        if (empty($data['code'])) throw new ApiException('请输入配置编码');
        if (empty($data['sort'])) throw new ApiException('请输入排序');
        $save['name'] = trim($data['name']);
        $save['sort'] = $data['sort'];
        $save['code'] = $data['code'] ;
        $save['note'] = $data['note'] ?? '';
        unset($data['id']);
        if ($id == 0) {
            // code重复性验证
            $count = $this->service->getUserCountByWhere([["code", '=', $save['code']], ["mark", "=", 1]]);
            if ($count > 0) throw new ApiException('系统中已存在相同的配置编码');
            $this->service->add($save);
        } else {
            $count = $this->service->getUserCountByWhere([["code", '=', $save['code']], ["id", "<>", $id], ["mark", "=", 1]]);
            if ($count > 0) throw new ApiException('系统中已存在相同的配置项值');
            $this->service->save($save, $id);
        }
        return message();

    }

    /**
     * 获取配置信息
     * @return array
     */
    public function getConfigData()
    {
        $code = request()->input('code', '');
        if (!$code) return message();
        $data = $this->convertData($this->service->getConfigData($code));
        return message($data);
    }



    /**
     * 提交配置更改
     * @return array
     */
    public function editConfigData()
    {
        $params = request()->all();
        if (empty($params['code'])) throw new ApiException('编码错误');
        $code = $params['code'];
        unset($params['code']);
        if (!$params) throw new ApiException('参数错误');
        $this->service->editConfigData($code, $params);
        return message();
    }

    /**
     * 转化数据
     *
     * @param array $configList  配置列表
     * @return array
     */
    protected function convertData(array $configList): array
    {
        if(!$configList) return $configList;
        $dataRes = [];
        foreach ($configList as $k => $v) {
            $v['options_arr'] = [];
            if ( $v['type'] == "checkbox-group"  || $v['type'] =='select' || $v['type'] =='radio-group') {
                $data = preg_split('/[\r\n]+/s', $v['options']);
                if ($data) {
                    $arr = [];
                    foreach ($data as $k=> $vt) {
                        $value = preg_split('/[:：]+/s', $vt);
                        $arr[$k]['label']=$value[1];
                        $arr[$k]['value']=$value[0];
                    }
                    $v['options_arr'] = $arr;
                }
            }
            if ($v['type'] == "checkbox-group") {
                $v['value'] = explode(",", $v['value']);
            }
            $dataRes[$k]=$v;
        }
        return array_values($dataRes);
    }


}
